package com.apache.common.plugins;

import com.alibaba.fastjson.JSON;
import com.apache.cache.service.impl.redis.RedisCoreFactory;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;

/**
 * @Description 访问黑白名单缓存处理(事后插件)
 * @Date 2021/01/25 22:57
 */
public class ZuulBlackCachePluginImpl implements CustomMethodPlugin {
    protected Logger log = LoggerFactory.getLogger(getClass());
    @Override
    public Object beforeInvoke(Map<String, Object> map) {
        String modelTypes = String.valueOf(map.get("modelTypes"));
        if(modelTypes.startsWith("d_")){
            String infoId = String.valueOf(map.get("sysZuulBlack.w_infoId"));//主键与useIp值相等
            List<Map<String,String>> list = (List)IusPluginUtil.getInstance().select("select * from sys_zuul_black where info_id='"+infoId+"'",0,0);
            Map<String,String> info = list.get(0);
            buildCacheInfo(info.get("useIp"),null,true);
        }
        return null;
    }

    @Override
    public Object doInvoke(Map<String, Object> map) {
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {
        String modelTypes = String.valueOf(map.get("modelTypes"));
        String infoId = String.valueOf(map.get("sysZuulBlack.w_infoId"));//主键与useIp值相等
        if(modelTypes.startsWith("i_") || modelTypes.startsWith("u_")){
            if(StrUtil.isNull(infoId)) {
                Map<String, Object> resultIds = (Map) map.get("resultIds");
                if (resultIds != null) {
                    infoId = String.valueOf(resultIds.get("sysZuulBlack_infoId"));
                }
            }
            List<Map<String,String>> list = (List)IusPluginUtil.getInstance().select("select * from sys_zuul_black where info_id='"+infoId+"'",0,0);
            Map<String,String> info = list.get(0);
            if("1".equalsIgnoreCase(info.get("enabled"))) {
                buildCacheInfo(info.get("useIp"), info, false);
            }else{
                buildCacheInfo(info.get("useIp"),null,true);
            }
        }
        return null;
    }

    private void buildCacheInfo(String key,Map<String,String> info, boolean isdel){
        Jedis jedis = null;
        try{
            jedis = RedisCoreFactory.getInstance().getJedis();
            jedis.select(10);
            if(isdel){
                jedis.hdel("black.white", key);
            }else{
                jedis.hsetnx("black.white",key, JSON.toJSONString(info));
            }
        }catch (Exception e){
        }finally{
            if(null != jedis){
                jedis.close();
            }
        }
    }
}
